require(["dojo/data/ItemFileReadStore", 
         "dijit/form/Select", 
         "dojox/grid/DataGrid", 
         "dojo/dom", 
         "dojo/dom-style", 
         "dojox/charting/Chart", 
         "dojox/charting/plot2d/Pie", 
         "dojo/request", 
         "dojo/domReady!" ], 
		function(ItemFileReadStore, Select, DataGrid, dom, domStyle, Chart, Pie, request){
	
	var stockId=0;
	
	distributionReturn=function(text){
		domStyle.set("distLong","width",text.split(":")[1]);
		dom.byId("distLong").innerHTML=text.split(":")[1];
		domStyle.set("distOut","width",text.split(":")[2]);
		dom.byId("distOut").innerHTML=text.split(":")[2];
		domStyle.set("distShort","width",text.split(":")[3]);
		dom.byId("distShort").innerHTML=text.split(":")[3];
	};
	
	distributionError=function(error){
		alert("Error: "+error);
	};
	
	popSelected = function(value){
		var tradesStore = new ItemFileReadStore({url: "/FinanceWeb/JsonTradeList?id="+stockId+"&ind="+value});
		tradeGrid.setStore(tradesStore);
		tradeGrid.update();
		dom.byId("profitImg").innerHTML="<IMG class='profitGraph' SRC='/FinanceWeb/profitGraph?id="+stockId+"&ind="+value+"'>";
		var inds=value.split(":");
		dom.byId("indGraph").innerHTML="<IMG class=sysVis SRC='/FinanceWeb/SystemGraph?id="+stockId+"&ind=plain%20wc'<BR>";
		for(var i=0;i<inds.length;i++){
			dom.byId("indGraph").innerHTML+="<IMG class='sysVis' SRC='/FinanceWeb/SystemGraph?id="+stockId+"&ind="+inds[i]+"'><BR>";	
		}
		//request("/FinanceWeb/Distribution?id="+stockId).then(distributionReturn, distributionError);
	};
	
	stockSelected = function(value){
		var tradeStore = new ItemFileReadStore({url: "/FinanceWeb/JsonTradeSet?id="+value});
		stockId=value;
		popSelect.setStore(tradeStore);
		popSelect.reset();
	};
	
	var layout = [[{'name': 'Date Opend', 'field': 'opendate', 'width': '150px'},
	              {'name': 'Open Price', 'field': 'open', 'width': '100px'},
	              {'name': 'Date Closed', 'field': 'closedate', 'width': '150px'},
	              {'name': 'Close Price', 'field': 'close', 'width': '100px'},
	              {'name': 'Running Profit', 'field': 'profit', 'width': '200px'},
	              {'name': 'Position Taken', 'field': 'position', 'width': '100px'}
	              ]];
	
	var stockStore = new ItemFileReadStore({url: "/FinanceWeb/JsonStockList"});
	var tradeStore = new ItemFileReadStore({url: "/FinanceWeb/JsonTradeSet?id=0"});
	var tradesStore = new ItemFileReadStore({url: "/FinanceWeb/JsonTradeList?id=0"});
	var popSelect = new Select({name: "popSelect",
		store: tradeStore,
		maxHeight: -1,
		onChange: popSelected}, "populationSelect");
	var stockSelect = new Select({name: "stockSelect",
									store: stockStore,
									maxHeight: -1,
									onChange: stockSelected}, "stockSelect");
	var tradeGrid = new DataGrid({ id: 'tradeGrid',
									store: tradesStore,
									structure: layout}, "tradeGrid");
	popSelect.startup();
	stockSelect.startup();
	tradeGrid.startup();
	
});